package com.yqRecite.controller;

import cn.hutool.crypto.SecureUtil;
import com.yqRecite.valiable.BaiduContent;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.Random;

@RestController
@CrossOrigin
@RequestMapping("translate")
public class TranslationController {

    @PostMapping("sentence")
    public Object translate(@RequestBody Map<String,String> data)
    {
        //获取请求参数
        String q = data.get("q");
        String from = data.get("from");
        String to = data.get("to");
        //随机数
        Random random = new Random(10);
        String salt = Integer.toString(random.nextInt());
        System.out.println("salt==>" +salt);
        //MD5加密
        //自定义的全局变量 appid和密钥
        String appid = BaiduContent.APPID + q + salt + BaiduContent.SECRET;
        String sign = SecureUtil.md5(appid);

        //封装请求参数
        MultiValueMap<String, String> paramMap = new LinkedMultiValueMap<>();
        paramMap.add("q",q);
        paramMap.add("from",from);
        paramMap.add("to",to);
        paramMap.add("appid", BaiduContent.APPID);
        paramMap.add("salt",salt);
        paramMap.add("sign",sign);
        String url = "http://api.fanyi.baidu.com/api/trans/vip/translate";
        //封装请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(paramMap,headers);

        //调用百度翻译API，发送请求，得到结果
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Object> response = restTemplate.postForEntity(url, httpEntity, Object.class);

        return response.getBody();
    }

}
